#ifdef DEVICE_PC_WATCHMEN_PCIE

#include "pcWatchmenPCIE.h"

#define BOARD_SWITCH_PIN D2 //输出 高平触发
#define BOARD_SWTICH_DOWN digitalWrite(BOARD_SWITCH_PIN, HIGH)
#define BOARD_SWTICH_UP digitalWrite(BOARD_SWITCH_PIN, LOW)

#define LOCK_PIN D1 //低电平 断开面板开关与主板
#define EXT_SW_LOCK digitalWrite(LOCK_PIN, LOW)
#define EXT_SW_UNLOCK digitalWrite(LOCK_PIN, HIGH)

#define BUZZER_PIN D5
#define BUZZER_OFF digitalWrite(LOCK_PIN, LOW)

#define POWER_STATE_PIN D7 // IO13 高电平为开机状态
#define POWER_STATE digitalRead(POWER_STATE_PIN)

#define CONFIG_EXT_SW_LOCK_ADD 1

#define BEMFA_MQTT_HOST "bemfa.com"
#define BEMFA_MQTT_PORT 9501

extern String hostname;
extern String password;
extern ESP8266WSYBoot boot;

BemfaMqtt bemfaMqtt;
String bemfaToken = "";
bool bufferBusy = false;
String bufferTopic = "";
String bufferMessage = "";

Ticker _shutdown_ticker;
Ticker _power_ticker;

volatile unsigned char power = 0xFF;
volatile unsigned char pullDownTimer = 0;
volatile unsigned char uploadStatus = 0;

#define LOCK_STATE_NONE 0xFF
#define LOCK_STATE_LOCK 0x01
#define LOCK_STATE_UNLOCK 0x00

unsigned char extSwLocker = 0;

//注册 Bemfa MQTT 回调，回调函数将收到的消息交给主进程处理
void register_bemfa_handle() {
    //淘宝红外
    String deviceType = "PCWatchmenPCIE";
    // deviceType.toLowerCase();
    String topic = hostname + "XX" + deviceType + "XX999";
    DEBUG_LOG("[DEV] subscription topic:");
    DEBUG_LOG_LN(topic);
    bemfaMqtt.onMessage(topic, [](const String &topic, const String &msg, AsyncMqttClient &mqttClient) {
        if (!bufferBusy) {
            bufferTopic = topic;
            bufferMessage = msg;
            bufferBusy = true;
        }
    });
}

void device_pin_init() {
    pinMode(BOARD_SWITCH_PIN, OUTPUT);
    pinMode(LOCK_PIN, OUTPUT);
    pinMode(BUZZER_PIN, OUTPUT);
    pinMode(POWER_STATE_PIN, INPUT);

    BOARD_SWTICH_UP;

    extSwLocker = config_read_byte(CONFIG_EXT_SW_LOCK_ADD);
    if (extSwLocker == 0xFF) {
        extSwLocker = LOCK_STATE_UNLOCK;
        // config_write_byte(CONFIG_EXT_SW_LOCK_ADD, false);

    } else if (extSwLocker == 0x01) {
        extSwLocker = LOCK_STATE_LOCK;
        // config_write_byte(CONFIG_EXT_SW_LOCK_ADD, false);

    } else {
        extSwLocker = LOCK_STATE_UNLOCK;
        // config_write_byte(CONFIG_EXT_SW_LOCK_ADD, false);
    }

    if (extSwLocker == LOCK_STATE_LOCK) {
        EXT_SW_LOCK; //锁定
    } else {
        EXT_SW_UNLOCK; //解锁
    }

    BUZZER_OFF; // 蜂鸣器暂时先关闭
}

void device_power_ticker() {
    static unsigned char _power = 0xFF;
    _power = POWER_STATE;
    if (power != _power) {
        power = _power;
        uploadStatus = 1;
    }
}

void device_shutdown_ticker() {
    DEBUG_LOG_LN("device_check_shutdown");
    if (!--pullDownTimer || !POWER_STATE) {
        BOARD_SWTICH_UP;
        _shutdown_ticker.detach();
    }
}

void device_upload_status() {
    String powerStr = "0";
    if (power) {
        powerStr = "1";
    }
    String extSwLockerStr = "0";
    if (extSwLocker) {
        extSwLockerStr = "1";
    }

    String deviceType = "PCWatchmenPCIE";
    String topic = hostname + "XX" + deviceType + "XX999/set";
    String msg = "state#" + powerStr + "#" + extSwLockerStr;
    DEBUG_LOG_LN(msg);
    bemfaMqtt.sendMessage(topic, msg);
    deviceType = "";
    topic = "";
    powerStr = "";
}

//主进程检查是否收到bemfa云的消息
void device_handle_messages(const String &topic, const String &msg) {
    if (topic == hostname + "XXPCWatchmenPCIEXX999") {
        //校验消息密码
        if (!msg.startsWith(password)) {
            return;
        }
        String _msg = msg.substring(password.length()+1);
        DEBUG_LOG("[DEV] onmessage:");
        DEBUG_LOG_LN(_msg);
        if (_msg.startsWith("state#")) {
            uploadStatus = 1;
            return;
        }

        if (_msg.startsWith("locker#1")) {
            extSwLocker = LOCK_STATE_LOCK;
            // config_write_byte(CONFIG_EXT_SW_LOCK_ADD, extSwLocker);
            EXT_SW_LOCK;
            uploadStatus = 1;
            return;
        }

        if (_msg.startsWith("locker#0")) {
            extSwLocker = LOCK_STATE_UNLOCK;
            // config_write_byte(CONFIG_EXT_SW_LOCK_ADD, extSwLocker);
            EXT_SW_UNLOCK;
            uploadStatus = 1;
            return;
        }

        if (_msg.startsWith("on#")) {
            BOARD_SWTICH_DOWN;
            delay(500);
            BOARD_SWTICH_UP;
            return;
        }

        if (_msg.startsWith("shutdown#")) {
            BOARD_SWTICH_DOWN;
            pullDownTimer = 10;
            _shutdown_ticker.attach(1, device_shutdown_ticker);
            return;
        }
    }
}

void device_setup() {
    DEBUG_LOG_LN("[DEV] setup");

    bemfaToken = bemfaMqtt.getBemfaToken();
    DEBUG_LOG("[DEV] bemfa token:");
    DEBUG_LOG_LN(bemfaToken);

    if (bemfaToken != "") {
        register_bemfa_handle();
        bemfaMqtt.setBemfaMqtt(BEMFA_MQTT_HOST, BEMFA_MQTT_PORT, bemfaToken);
        bemfaMqtt.begin();
    } else {
        DEBUG_LOG_LN("[DEV] bemfa token is empty!");
        boot.ledWait();
    }
}

void device_loop() {
    if (bufferBusy) {
        DEBUG_LOG_LN(bufferMessage);
        device_handle_messages(bufferTopic, bufferMessage);
        bufferTopic = "";
        bufferMessage = "";
        bufferBusy = false;
    }
    if (uploadStatus) {
        device_upload_status();
        uploadStatus = 0;
    }
}

#endif